<template>
  <div class="app-container">
    <div v-show="!modifyInfo.visible && !detailInfo.visible">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-print>
            <el-button @click="print()">打印</el-button>
          </template>
          <template v-slot:filter-download>
            <el-button @click="exportExcel()">导出excel</el-button>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </table-container>
    </div>
    <order-modify
      v-if="modifyInfo.visible"
      :order-id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :receive-id="modifyInfo.receiveId"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />
    <order-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :id="detailInfo.data.id"
      @returnBack="getList"
    />
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <AddByReceive
      v-if="addByReceiveDialog.visible"
      v-model:visible="addByReceiveDialog.visible"
      @callback="addReceiveBack"
    />
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
    <page-dialog
      v-if="dialogPathInfo.visible"
      :title="dialogPathInfo.title"
      v-model:visible="dialogPathInfo.visible"
      :width="dialogPathInfo.width"
      :bt-loading="dialogPathInfo.btLoading"
      :bt-list="dialogPathInfo.btList"
      @reset="close"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formInfo.ref"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :rules="formInfo.rules"
        :label-width="formInfo.labelWidth"
      >
        <template v-slot:form-depotName>{{
          dialogPathInfo.row.depotName
        }}</template>
        <template v-slot:form-deptName>{{
          dialogPathInfo.row.deptName
        }}</template>
        <template v-slot:form-transferDepotName>
          <el-input
            v-model="formInfo.data.transferDepotName"
            class="not-mongolia"
            type="input"
            :required="true"
            :disabled="true"
            placeholder="请选择入库仓库"
          >
            <template #append>
              <el-icon @click="selectStoreDepot"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
      </page-form>
      <dialog-table
        v-if="dialogTableInfo.data.length"
        ref="dialogTableRef"
        v-model:data="dialogTableInfo.data"
        :field-list="dialogTableInfo.fieldList"
        :highlight-row="true"
        :tab-index="true"
        :check-box="false"
        :pager="false"
        @handleEvent="handleDialogEvent"
      >
      </dialog-table>
    </page-dialog>
    <select-depot
      v-if="selectDepotInfo.visible"
      v-model:show-dialog="selectDepotInfo.visible"
      :check-box="false"
      :query="selectDepotInfo.query"
      :highlight-row="true"
      :check-lock="true"
      :save-empty="true"
      @callback="selectDepotCallBack"
    />
  </div>
</template>

<script setup name="estimationConfirmationOrder">
import NewPageFilter from '@/components/NewPageFilter/index'
import TableContainer from '@/components/TableContainer/index'
import DialogTable from '@/components/DialogTable/index'
import SelectDepot from '@/components/SelectDepot/index'
import {
  getEstimationConfirmationOrderCustomizeListPage,
  auditEstimationConfirmation,
  submitEstimationConfirmation,
  confirmEstimationConfirmation,
  deleteEstimationConfirmation,
  estimationConfirmationPrintList,
  estimationConfirmationExcelList,
  getDepotCirculationPath,
  estimationConfirmationRevoke,
  estimationConfirmationRevokeOrder,
} from '@/api/stock.js'
import OrderModify from './modify'
import OrderDetail from './details'
import AddByReceive from './addByReceive'
import { fatchTemplateByCode } from '@/api/base'
import { getDepotsDefault } from '@/api/core'
import PageDialog from '@/components/PageDialog/index'
import PageForm from '@/components/PageForm/index'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
const { proxy } = getCurrentInstance()

const dialogInfo = reactive({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      depotAuth: {
        asTbName: 'estimation_confirmation_order',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
      deptAuth: {
        asTbName: 'estimation_confirmation_order',
        columnName: 'dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'deptAuth',
      },
      supplierAuth: {
        asTbName: 'estimation_confirmation_order',
        columnName: 'supplier_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'supplierAuth',
      },
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '暂估入库单导入',
      event: create,
      show: proxy.$permission('estimationConfirmationOrder:add'),
    },
    {
      type: 'slot',
      value: 'download',
      show: proxy.$permission('estimationConfirmationOrder:excelOrder'),
    },
    {
      type: 'slot',
      value: 'print',
      show: proxy.$permission('estimationConfirmationOrder:printOrder'),
    },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('estimationConfirmationOrder:submit'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '修改',
        event: update,
        show: proxy.$permission('estimationConfirmationOrder:update'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 2
        },
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('estimationConfirmationOrder:del'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '撤回',
        event: revoke,
        show: proxy.$permission('estimationConfirmationOrder:revoke'),
        ifRender: function (row) {
          return row.status === 2 || row.status === 3
        },
      },

      {
        label: '审核',
        event: examine,
        show: proxy.$permission('estimationConfirmationOrder:examine'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '确认',
        event: confirm,
        show: proxy.$permission('estimationConfirmationOrder:confirm'),
        ifRender: function (row) {
          return row.status === 3
        },
      },
      {
        label: '暂估撤回',
        event: estimatedRevoke,
        popconfirmText: '是否整单暂估撤回？',
        show: proxy.$permission('estimationConfirmationOrder:revokeOrder'),
        ifRender: function (row) {
          return row.status === 4
        },
      },
    ],
  },
})
const dialogTableInfo = reactive({
  data: [],
  fieldList: [{ label: '暂估确认路径', value: 'name' }],
})
// 弹窗相关
const dialogPathInfo = reactive({
  title: '暂估确认',
  visible: false,
  type: '',
  width: '670px',
  btLoading: false,
  row: {},
  path: {},
  btList: [
    { label: '关闭', type: '', icon: '', event: close, show: true },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      disabled: true,
      event: stockAndEstimation,
      saveLoading: false,
      show: true,
    },
  ],
})
const selectDepotInfo = reactive({
  visible: false,
  query: {
    depotAuth: 'id',
    idNot: '',
    status: 1,
    useTypeId: 1,
  },
})
const formInfo = reactive({
  ref: null,
  data: {
    id: '',
    transferDepotName: '',
    transferDeptName: '',
    transferDepotId: '',
    transferDeptId: '',
  },
  fieldList: [
    {
      label: '暂估入库仓库',
      value: 'depotName',
      type: 'slot',
    },
    {
      label: '暂估入库部门',
      value: 'deptName',
      type: 'slot',
    },
    {
      label: '确认入库仓库',
      value: 'transferDepotName',
      type: 'slot',
    },
    {
      label: '确认入库部门',
      value: 'transferDeptName',
      type: 'input',
      placeholder: '确认入库部门',
      disabled: true,
    },
  ],
  rules: {
    transferDepotName: [
      {
        required: true,
        message: '请输入仓库',
        trigger: 'blur',
      },
    ],
  },
  labelWidth: '120px',
})
const modifyInfo = reactive({
  visible: false,
  receiveId: '',
  id: '',
  title: '',
})
const detailInfo = reactive({
  visible: false,
  data: {},
})
const preferenceInfo = reactive({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})
const addByReceiveDialog = reactive({
  visible: false,
})
const page = reactive({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (
                el.code === 'estimationConfirmationOrder' &&
                el.url === val.url
              ) {
                modifyInfo.visible = false
                detailInfo.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  proxy.$nextTick(() => {
                    detailInfo.visible = true
                    detailInfo.data = { id: val.businessId }
                    sessionStorage.setItem('storeRowId', val.businessId)
                  })
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})
let obj = {
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'estimation_confirmation_status',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

function handleClose() {
  dialogInfo.visible = false
}
function pageInfo(obj) {
  page.curPage = obj.curPage
  page.pageSize = obj.pageSize
}
function checkConfirm() {
  if (dialogInfo.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.type === 'print') {
    printList()
  }
  dialogInfo.visible = false
  dialogInfo.msg = ''
}
function exportExcel() {
  dialogInfo.visible = true
  dialogInfo.type = 'excel'
  dialogInfo.msg = '请选择数据导出范围'
  dialogInfo.btList[1].label = '导出'
  dialogInfo.flag = true
}
function exportExcelList() {
  let params = {
    ...filterInfo.query,
    ...page,
    page: dialogInfo.flag,
  }
  estimationConfirmationExcelList(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
async function print() {
  dialogInfo.visible = true
  dialogInfo.type = 'print'
  dialogInfo.msg = '请选择当数据打印范围'
  dialogInfo.btList[1].label = '打印'
  dialogInfo.flag = true
}
//打印
function printList() {
  fatchTemplateByCode({
    resourceCode: 'estimationConfirmationOrder:printOrder',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogInfo.flag)
    }
  })
}
function getPrintData(temp, flag) {
  let query = {
    customizeDto: filterInfo.query,
  }
  let params = {
    ...query,
    ...page,
    page: flag,
  }
  estimationConfirmationPrintList(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function returnModify() {
  if (modifyInfo.id) {
    getList()
  } else {
    search()
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.query.queryMap = {}
  let arr = []
  filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
// 获取列表
async function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页

  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
//删除
function remove(row) {
  deleteEstimationConfirmation([row.id]).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function revoke(row = undefined) {
  //撤回
  estimationConfirmationRevoke(row.id).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function estimatedRevoke(row = undefined) {
  //暂估整单撤回
  estimationConfirmationRevokeOrder(row.id).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
//创建
function create() {
  addByReceiveDialog.visible = true
}
function addReceiveBack(data) {
  proxy.$nextTick(() => {
    let id = data.data.id
    addByReceiveDialog.visible = false
    modifyInfo.receiveId = id
    modifyInfo.id = ''
    modifyInfo.title = '新增暂估确认单'
    modifyInfo.visible = true
  })
}
function update(row) {
  //修改
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.id = row.id
  modifyInfo.receiveId = ''
  modifyInfo.title = '修改暂估确认单'
  modifyInfo.visible = true
}
//提交
function submit(row = undefined) {
  submitEstimationConfirmation([row.id]).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function examine(row = undefined) {
  //审核
  auditEstimationConfirmation(row.id).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function getDepotsDefaults() {
  let systemConfig = proxy.$store.state.permission.systemConfig
  if (systemConfig.default_receive_depot == 1) {
    //查询默认仓库
    getDepotsDefault().then((resp) => {
      if (resp && resp.success) {
        let data = resp.data
        if (data) {
          formInfo.data.transferDepotId = data.id
          formInfo.data.transferDepotName = data.name
          formInfo.data.transferDeptName = data.deptName || ''
          formInfo.data.transferDeptId = data.deptId || ''
          dialogPathInfo.btList[1].disabled = true
          getStorePath()
        }
      }
    })
  } else if (systemConfig.default_receive_depot == 2) {
    let depotName = proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceName
      : ''
    formInfo.data.transferDepotName = depotName
    formInfo.data.transferDepotId = proxy.$store.state.user.userInfo
      .coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
      : ''
    let deptName = proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : ''
    formInfo.data.transferDeptName = deptName
    formInfo.data.transferDeptId = proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : ''
    if (depotName) {
      dialogPathInfo.btList[1].disabled = true
      getStorePath()
    }
  }
}
function confirm(row = undefined) {
  //确认
  dialogPathInfo.visible = true
  dialogPathInfo.row = row
  formInfo.data.id = row.id
  // selectDepotInfo.query.idNot = row.depotId;
  getDepotsDefaults()
}
function handleDialogEvent(event, data) {
  if (event === 'tableClickRow' && data) {
    dialogPathInfo.path = data.value
  }
}
//关闭弹窗
function close() {
  formInfo.data.id = ''
  formInfo.data.transferDepotId = ''
  formInfo.data.transferDeptId = ''
  formInfo.data.transferDepotName = ''
  formInfo.data.transferDeptName = ''
  selectDepotInfo.query.idNot = ''
  dialogTableInfo.data = []
  dialogPathInfo.visible = false
  dialogPathInfo.btList[1].disabled = true
}
//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.data = row
  detailInfo.visible = true
}
//选择仓库
function selectStoreDepot() {
  selectDepotInfo.visible = true
}
function selectDepotCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.data.transferDepotId = data.id
    formInfo.data.transferDepotName = data.name
    formInfo.data.transferDeptName = data.deptName || ''
    formInfo.data.transferDeptId = data.deptId || ''
    dialogPathInfo.btList[1].disabled = true
    getStorePath()
  } else {
    formInfo.data.transferDepotId = ''
    formInfo.data.transferDepotName = ''
    formInfo.data.transferDeptName = ''
    formInfo.data.transferDeptId = ''
  }
}
function getStorePath() {
  let param = {
    firstDepotId: formInfo.data.transferDepotId,
    lastDepotId: dialogPathInfo.row.depotId,
  }
  getDepotCirculationPath(param).then((res) => {
    if (res && res.success) {
      dialogTableInfo.data = res.data
      if (res.data.length > 0) {
        dialogPathInfo.path = res.data[0].value
        // proxy.$refs.dialogTableRef.setCurrentRow(res.data[0], true)
      }
      dialogPathInfo.btList[1].disabled = false
    }
  })
}
function stockAndEstimation() {
  formInfo.ref.validate((valid) => {
    if (valid) {
      let id = formInfo.data.id
      if (dialogTableInfo.data.length) {
        let params = {
          id: id,
          path: dialogPathInfo.path,
        }
        confirmEstimationConfirmation(params).then((res) => {
          if (res && res.success) {
            getList()
            close()
          }
        })
      } else {
        let params = {
          id: id,
          //path: [dialogPathInfo.row.depotId, formInfo.data.transferDepotId],
          path: [formInfo.data.transferDepotId, dialogPathInfo.row.depotId],
        }
        confirmEstimationConfirmation(params).then((res) => {
          if (res && res.success) {
            getList()
            close()
          }
        })
      }
    }
  })
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.data = {}
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'EstimationConfirmationOrderList-com.slip.spd.entity.vo.stock.EstimationConfirmationOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = getEstimationConfirmationOrderCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
